package com.loe.ktui.custom

import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.util.TypedValue
import android.view.Gravity
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.core.view.isVisible
import com.loe.ktui.*
import com.loe.ktui.util.KtColor
import com.loe.picker.PickerDialog
import com.loe.picker.util.PickerBean
import kotlinx.android.synthetic.main.kt_view_form_select.view.*
import org.json.JSONArray
import org.json.JSONObject

open class UiFormSelectView(id: String? = null) : UiFrameLayout(id)
{
    override var width: Any? = MATCH_PARENT

    var isInfo: Boolean? = null
    var title: CharSequence? = null
    var notNull: Boolean? = null
    var text: CharSequence? = null
    var unit: CharSequence? = null
    var hint: CharSequence? = null
    var formGravity: Int? = null
    var textSize: Any? = 15
    var titleSize: Any? = null
    var textColor: Int? = null
    var titleColor: Int? = null
    var unitColor: Int? = null
    var titleLeft: Any? = null
    var titleLen: Any? = null
    var tailLen: Any? = null

    var onText: (KtFormSelectView.(s: String) -> Unit)? = null
    fun onText(onText: KtFormSelectView.(s: String) -> Unit)
    {
        this.onText = onText
    }

    var onSelect: (KtFormSelectView.(i: Int, bean: PickerBean) -> Unit)? = null
    fun onSelect(onSelect: KtFormSelectView.(i: Int, bean: PickerBean) -> Unit)
    {
        this.onSelect = onSelect
    }

    fun initUI(context: Context, view: KtFormSelectView)
    {
        super.initUI(context, view)

        isInfo?.let { view.isInfo = it }
        title?.let { view.title = it }
        notNull?.let { view.notNull = it }
        text?.let { view.text = it }
        unit?.let { view.unit = it }
        view.hint = hint ?: (if (isInfo == true) "" else "请选择")
        formGravity?.let { view.formGravity = it }
        textSize?.let { view.setTextSizePx(it.distFloat) }
        titleSize?.let { view.setTitleSizePx(it.distFloat) }
        textColor?.let { view.textColor = it }
        titleColor?.let { view.titleColor = it }
        unitColor?.let { view.unitColor = it }
        titleLeft?.let { view.titleLeft = it.distFloat }
        titleLen?.let { view.titleLen = it.distFloat }
        tailLen?.let { view.tailLen = it.distFloat }

        onText?.let { onText -> view.setTextListener { view.onText(it) } }
        onSelect?.let { onSelect -> view.setOnSelectListener { i, bean -> view.onSelect(i, bean) } }
    }

    override fun createView(context: Context, parent: ViewGroup?): KtFormSelectView
    {
        return KtFormSelectView(context).also()
        {
            initUI(context, it)
            addToParent(parent, it)
        }
    }
}

fun Any.ui_FormSelectView(id: String? = null, block: (UiFormSelectView.() -> Unit)? = null): UiFormSelectView
{
    val ui = UiFormSelectView(id)
    block?.let { ui.it() }
    if (this is UiGroup) addChild(ui)
    return ui
}

/** 表单选择View */
open class KtFormSelectView : KtFrameLayout
{
    constructor(context: Context) : super(context)
    {
        onCreate(null)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    {
        onCreate(attrs)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
    {
        onCreate(attrs)
    }

    private fun onCreate(attrs: AttributeSet?)
    {
        val root = inflate(context, R.layout.kt_view_form_select, null) as ViewGroup?
        addView(root, MATCH_PARENT, MATCH_PARENT)

        attrs?.let()
        {
            val typedArray = context.obtainStyledAttributes(it, R.styleable.KtFormSelectView)

            // isInfo
            isInfo = typedArray.getBoolean(R.styleable.KtFormSelectView_kt_form_isInfo, false)
            // title
            title = typedArray.getString(R.styleable.KtFormSelectView_kt_form_title) ?: ""
            // notNull
            notNull = typedArray.getBoolean(R.styleable.KtFormSelectView_kt_form_notNull, false)
            // noRipple
            noRipple = typedArray.getBoolean(R.styleable.KtFormSelectView_kt_form_noRipple, false)
            // text
            text = typedArray.getString(R.styleable.KtFormSelectView_kt_form_text) ?: ""
            // hint
            hint = typedArray.getString(R.styleable.KtFormSelectView_kt_form_hint) ?: if (isInfo) "" else "请选择"
            // hintColor
            hintColor = typedArray.getColor(R.styleable.KtFormSelectView_kt_form_hintColor, KtColor.lineDeep)
            // unit
            unit = typedArray.getString(R.styleable.KtFormSelectView_kt_form_unit) ?: ""

            // formGravity
            formGravity = typedArray.getInt(R.styleable.KtFormSelectView_kt_form_gravity, Gravity.LEFT)
            // size
            textSize = dp(typedArray.getDimension(R.styleable.KtFormSelectView_kt_form_textSize, ktPx(15).toFloat()))
            titleSize = dp(typedArray.getDimension(R.styleable.KtFormSelectView_kt_form_titleSize, ktPx(15).toFloat()))
            // title_color
            titleColor = typedArray.getColor(R.styleable.KtFormSelectView_kt_form_titleColor, KtColor.grayDeep)
            // unit_color
            unitColor = typedArray.getColor(R.styleable.KtFormSelectView_kt_form_unitColor, KtColor.grayDeep)
            // text_color
            textColor = typedArray.getColor(R.styleable.KtFormSelectView_kt_form_textColor, KtColor.text)
            // titleLeft
            titleLeft = typedArray.getDimension(R.styleable.KtFormSelectView_kt_form_titleLeft, ktPx(15).toFloat())
            // titleLen
            titleLen = typedArray.getDimension(R.styleable.KtFormSelectView_kt_form_titleLen, ktPx(110).toFloat())
            // tailLen
            tailLen = typedArray.getDimension(R.styleable.KtFormSelectView_kt_form_tailLen, ktPx(6).toFloat())

            typedArray.recycle()
        }


        if (minimumHeight > 0)
        {
            root?.minimumHeight = minimumHeight
        }
    }

    var isInfo: Boolean = false
        set(value)
        {
            field = value
            imageArrow.isVisible = !value
        }

    var notNull = true
        set(value)
        {
            field = value
            textNotNull.visibility = if (value && title.isNotEmpty()) VISIBLE else INVISIBLE
        }

    var noRipple = false
        set(value)
        {
            field = value
            if(noRipple) viewRoot.setBackgroundColor(KtColor.alpha)
        }

    var title: CharSequence
        get() = textTitle.text
        set(value)
        {
            textTitle.text = value
            notNull = notNull
        }

    var text: CharSequence
        get() = textView.text.trim()
        set(value)
        {
            textView.text = value
        }

    val string get() = textView.text.trim().toString()

    val stringOrHint get() = textView.text.trim().toString().ifEmpty { hint.toString() }

    var code = ""

    var data = JSONObject()

    var hint: CharSequence
        get() = textView.hint
        set(value)
        {
            textView.hint = value
        }

    var hintColor = 0
        set(value)
        {
            field = value
            textView.setHintTextColor(value)
        }

    var unit: CharSequence
        get() = textUnit.text
        set(value)
        {
            textUnit.isVisible = value.isNotEmpty()
            textUnit.text = value
        }

    var formGravity = Gravity.RIGHT
        set(value)
        {
            field = value
            textView.gravity = value
        }

    var titleSize = 0f
        set(value)
        {
            field = value
            textTitle.textSize = titleSize
        }

    var textSize = 0f
        set(value)
        {
            field = value
            textTitle.textSize = textSize
            textView.textSize = textSize
            textUnit.textSize = textSize
        }

    var titleLeft = 0f
        set(value)
        {
            field = value
            textTitle.marginLeftPx = value.toInt()
        }

    var titleLen = 0f
        set(value)
        {
            field = value
            textView.setPadding(value.toInt(), ktPx(6), tailLen.toInt(), ktPx(6))
        }

    var tailLen = 0f
        set(value)
        {
            field = value
            textView.setPadding(titleLen.toInt(), ktPx(5), value.toInt(), ktPx(5))
        }

    var titleColor = KtColor.grayDeep
        set(value)
        {
            field = value
            textTitle.setTextColor(value)
        }

    var unitColor = KtColor.grayDeep
        set(value)
        {
            field = value
            textUnit.setTextColor(value)
        }

    var textColor = KtColor.text
        set(value)
        {
            field = value
            textView.setTextColor(value)
        }

    fun setTitleSizePx(px: Float)
    {
        textTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, px)
    }

    fun setTextSizePx(px: Float)
    {
        textTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, px)
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, px)
        textUnit.setTextSize(TypedValue.COMPLEX_UNIT_PX, px)
    }

    val length get() = string.length

    fun isEmpty(): Boolean = string.isEmpty()

    private fun dp(pxValue: Float): Float
    {
        val scale = resources.displayMetrics.density
        return (pxValue + 0.5f) / scale
    }

    fun setTextListener(initText: String? = null, onText: (s: String) -> Unit)
    {
        textView.setTextListener(initText, onText)
    }

    var pickerSingle: PickerDialog? = null
        private set

    fun setSinglePicker(js: JSONArray, callback: ((PickerBean) -> Unit)? = null)
    {
        var selectFlag = true
        pickerSingle = PickerDialog(context, js)
        { i, bean ->
            if (selectFlag)
            {
                if (bean.code.isEmpty())
                {
                    text = ""
                } else
                {
                    text = bean.name
                }
                code = bean.code
                data = bean.data
                callback?.invoke(bean)
                onSelectListener?.invoke(i, bean)
            }
        }
        setOnClickListener()
        {
            if (!isInfo)
            {
                hideSoft()
                selectFlag = false
                pickerSingle?.selectCode(code)
                selectFlag = true
                pickerSingle?.show()
            }
        }
    }

    fun select(code: String)
    {
        pickerSingle?.selectCode(code)
    }

    private var onSelectListener: ((i: Int, bean: PickerBean) -> Unit)? = null

    fun setOnSelectListener(listener: (i: Int, bean: PickerBean) -> Unit)
    {
        this.onSelectListener = listener
    }

    private fun hideSoft()
    {
        (context as Activity).runCatching()
        {
            val view = this.currentFocus
            val inputMethodManager = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputMethodManager.hideSoftInputFromWindow(view!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
            view.clearFocus()
        }
    }
}